package com.example.listener;

import com.example.latch.DbLeaderLatch;
import com.example.latch.LeaderLatch;
import com.example.latch.LeaderLatchRun;
import com.example.service.SysCdcListenerService;
import com.example.utils.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;

@Service
public class SysCdcListenerListener implements InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${jdbc.host}")
    private String host;

    @Value("${jdbc.port}")
    private int port;

    @Value("${jdbc.db}")
    private String db;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.driverClassName}")
    private String driverClassName;

    private LeaderLatch leaderLatch;

    @Resource
    private SysCdcListenerService sysCdcListenerService;

    @Override
    public void afterPropertiesSet() throws Exception {
        Connection connection = JdbcUtils.getConnection(host, port, db, username, password, driverClassName);
        this.leaderLatch = new DbLeaderLatch(connection, new LeaderLatchRun() {
            @Override
            public void run() {
                sysCdcListenerService.startAll();
            }
        });
        this.leaderLatch.start();
    }

    @Override
    public void destroy() throws Exception {
        this.sysCdcListenerService.stopAll();
        this.leaderLatch.stop();
    }
}
